from flask import Blueprint, render_template, jsonify, request, current_app
from .file_manager import FileManager
import os
from flask_login import login_required, current_user
from . import user_db

bp = Blueprint('main', __name__)
file_manager = FileManager()

@bp.route('/')
@login_required
def index():
    """主页路由"""
    try:
        # 检查模板文件是否存在
        template_path = os.path.abspath('templates/file_list.html')
        if not os.path.exists(template_path):
            raise Exception(f"模板文件不存在: {template_path}")
            
        source_files = file_manager.list_remote_files()
        destination_files = file_manager.list_destination_files()
        
        # 打印调试信息
        print(f"源文件列表: {source_files}")
        print(f"目标文件列表: {destination_files}")
        print(f"源路径: {file_manager.ssh_manager.config['paths']['source_path']}")
        
        return render_template(
            'file_list.html',
            source_files=source_files if source_files else [],
            destination_files=destination_files
        )
    except Exception as e:
        print(f"错误: {str(e)}")  # 打印错误信息
        return f"发生错误: {str(e)}", 500

@bp.route('/transfer', methods=['POST'])
@login_required
def transfer_file():
    """传输文件"""
    try:
        filename = request.form.get('filename')
        if not filename:
            return jsonify({'success': False, 'message': '未指定文件名'})
            
        # 使用 file_manager 的配置路径
        source_path = os.path.join(file_manager.ssh_manager.config["paths"]["source_path"], filename)
        dest_path = os.path.join(file_manager.ssh_manager.config["paths"]["destination_path"], filename)
        
        # 确保目标目录存在
        dest_dir = os.path.dirname(dest_path)
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)
            
        # 执行文件传输
        file_manager.transfer_file(filename)
        
        # 记录操作日志
        user_db.log_operation(
            current_user.id,
            'transfer',
            filename,
            True
        )
        return jsonify({'success': True, 'message': f'文件 {filename} 传输成功'})
            
    except Exception as e:
        # 记录错误日志
        user_db.log_operation(
            current_user.id,
            'transfer',
            filename,
            False,
            str(e)
        )
        return jsonify({'success': False, 'message': str(e)})

@bp.route('/destination-files')
def get_destination_files():
    """获取目标服务器文件列表"""
    try:
        path = request.args.get('path', '')
        files = file_manager.list_destination_files(path)
        return jsonify({
            'status': 'success',
            'files': files
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/check-file-exists', methods=['POST'])
def check_file_exists():
    """检查文件是否存在"""
    try:
        filename = request.form['filename']
        dest_path = os.path.join(file_manager.ssh_manager.config["paths"]["destination_path"], filename)
        exists = os.path.exists(dest_path)
        return jsonify({
            'status': 'success',
            'exists': exists
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/refresh-source-files')
@login_required
def refresh_source_files():
    path = request.args.get('path', '')
    files = file_manager.list_remote_files(path)
    return jsonify({'files': files if files else []})

@bp.route('/get-folder-contents')
@login_required
def get_folder_contents():
    folder_path = request.args.get('path', '')
    files = file_manager.list_remote_files(folder_path)
    return jsonify({'files': files})
